<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// +----------------------------------------------------------------------+
// | Treacle PHP Framework Version 0.10                                   |
// +----------------------------------------------------------------------+
// | Copyright (c) 2007 Treacle.cn All rights reserved.					  |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the 'License');      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an 'AS IS' BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: BoPo <ibopo@126.com>										  |
// +----------------------------------------------------------------------+
/**
 * Treacle 核心类文件
 *
 * @author BoPo <ibopo@126.com>
 * @link http://www.treacle.cn/
 * @copyright Copyright &copy; 2007 Treacle
 * @license http://www.treacle.cn/license/
 * @version $Id$
 */
/**
 * Treacle 核心类
 *
 * @author BoPo <ibopo@126.com>
 * @since 0.10
 * @version $Id$
 */
class Treacle
{
	private static $instance;
	private $_models	= array();
	private $_helpers	= array();
	private $_plugins	= array();
	private $_vendors	= array();
	private $_varmap	= array('input'=>'in','session'=>'sess');
	/**
	 * 构造函数
	 * @access public
	 */
	public function __construct()
	{
		self::$instance = &$this;
		$this->uri 		= new TRouter();
		$this->view 	= new TTemplate();
		$this->_autoloader();
	}
	/**
	 * 获得 $instance
	 * @access public
	 * @return object
	 */
	public static function get_instance()
	{
		return self::$instance;
	}
	/**
	 * __get
	 *
	 * @return $var
	 */
	private function __get($var)
	{
		return isset($this->$var)?$this->$var:null;
	}
	/**
	 * __set
	 *
	 * @return $var
	 */
	private function __set($var,$value)
	{
		if (isset($this->$var))
		{
			throw new TInvalidOperationException('object_property_exist');
		}
		$this->$var = $value;
	}
	/**
	 * 加载 library 方法
	 * 
	 * @access protected
	 * @param mixed $library
	 * @return void
	 */
	protected function library($library)
	{
		if ($library == '')	return false;
		$args = func_get_args();
		foreach ($args as $class)
		{
			$this->_load_class($class);
		}
	}
	/**
	 * 加载 service 方法
	 * 
	 * @access protected
	 * @param mixed $service
	 * @return  void
	 */
	protected function service($service='')
	{
		if ($service == '')	return false;
		$args = func_get_args();
		foreach ($args as $class)
		{
			$class 	= str_replace(EXT,'',$class);
			$name 	= ucfirst($class);
			if(!class_exists($name))
			{
				if (!file_exists(BASEPATH.'services/'.$name.EXT))
				{
					throw new TSystemException("Unable to load the requested class: ".$class);
				}
				include_once(BASEPATH.'services/'.ucfirst($class).EXT);
			}
			$class 		= strtolower($class);
			$classvar 	= ( ! isset($this->_varmap[$class])) ? $class : $this->_varmap[$class];
			$this->$classvar = new $name;
		}
	}
	/**
	 * 加载 Model 方法
	 * 
	 * @access	protected
	 * @param	string	model name
	 * @param	string	set model name
	 * @param	mixed
	 * @return	void
	 */
	protected function model($model,$name='',$db_conn = FALSE)
	{
		if ($model == '')
		{
			return;
		}
		if (strpos($model, '/') === FALSE)
		{
			$path = '';
		}
		else
		{
			$x		= explode('/', $model);
			$model	= end($x);
			unset($x[count($x)-1]);
			$path	= implode('/', $x).'/';
		}
		if($name =='')
		{
			$name = $model;
		}
		if (!file_exists(APPPATH.'models/'.$path.strtolower($model).EXT))
		{
			throw new TSystemException('Unable to locate the model you have specified: '.strtolower($model));
		}
		if ($db_conn !== FALSE AND ! class_exists('DB'))
		{
			if ($db_conn === TRUE)
			{
				$db_conn = '';
			}
			$this->database($db_conn,FALSE,TRUE);
		}
		if (!class_exists('Model'))
		{
			require_once(BASEPATH.'TModel'.EXT);
		}
		require_once(APPPATH.'models/'.$path.$model.EXT);
		$model = ucfirst($model);
		$this->$name = new $model();
		$this->_models[] = $name;
	}
	/**
	 * 加载数据库方法
	 * 
	 * @access	protected
	 * @param	string	数据库参数
	 * @param	bool	是否返回一个对象
	 * @param	bool	是否使用 active record
	 * @return	object
	 */
	protected function database($params = '', $return = FALSE, $active_record = FALSE)
	{
		if (class_exists('DB') AND $return == FALSE AND $active_record == FALSE)
		{
			return FALSE;
		}
		require_once(BASEPATH.'database/DB'.EXT);
		if ($return === TRUE) return DB($params, $active_record);
		$this->db = DB($params, $active_record);
	}
	/**
	 * 加载缓存方法
	 *
	 * @access protected
	 * @param string $params
	 * @param bool $return
	 * @return object
	 */
	protected function cache($params = 'file', $return = FALSE)
	{
		if(isset($this->cache))	return false;
		require(BASEPATH.'caching/Cache'.EXT);
		if ($return === TRUE) return CACHE($params);
		$this->cache = CACHE($params);
	}
	/**
	 * 加载助手函数库文件
	 * 
	 * @access	protected
	 * @param	mixed
	 * @return	void
	 */
	protected function helper($helpers = array())
	{
		if ( ! is_array($helpers))
		{
			$helpers = array($helpers);
		}
		foreach ($helpers as $helper)
		{
			$helper = strtolower(str_replace(EXT, '', 'helper_'.str_replace('_helper', '', $helper)));
			if (isset($this->_helpers[$helper])) continue;
			if (file_exists(BASEPATH.'helpers/'.$helper.EXT))
			{
				require_once(BASEPATH.'helpers/'.$helper.EXT);
			}
			else
			{
				throw new TSystemException('Unable to load the requested file: helpers/'.$helper.EXT);
			}
			$this->_helpers[$helper] = TRUE;
		}
	}
	/**
	 * 加载插件文件
	 * 
	 * @access	protected
	 * @param	mixed
	 * @return	void
	 */
	protected function plugin($plugins = array())
	{
		if ( ! is_array($plugins))
		{
			$plugins = array($plugins);
		}
		foreach ($plugins as $plugin)
		{
			$plugin = strtolower(str_replace(EXT, '', 'plugin_'.str_replace('_plugin', '', $plugin)));
			if (isset($this->_helpers[$plugin])) continue;
			if (file_exists(APPPATH.'plugins/'.$plugin.EXT))
			{
				require_once(APPPATH.'plugins/'.$plugin.EXT);
			}
			else
			{
				throw new TSystemException('Unable to load the requested file: plugins/'.$plugin.EXT);
			}
			$this->_helpers[$plugin] = TRUE;
		}
	}
	/**
	 * 加载用户定义类库和函数库
	 * 
	 * @access	protected
	 * @param	array
	 * @return	void
	 */
	protected function vendor($vendors = array())
	{
		if ( ! is_array($vendors))
		{
			$vendors = array($vendors);
		}
		foreach ($vendors as $vendor)
		{
			if (isset($this->_vendors[$vendor]))
			{
				continue;
			}
			if (file_exists(APPPATH.'vendors/'.$vendor.EXT))
			{
				require_once(APPPATH.'vendors/'.$vendor.EXT);
			}
			else
			{
				throw new TSystemException('Unable to load the requested file: vendors/'.$vendor.EXT);
			}
			$this->_vendors[$vendor] = TRUE;
		}
	}
	/**
	 * 包含类文件函数
	 * 
	 * @access	private
	 * @param 	string	类库的名称
	 * @return 	void
	 */
	private function _load_class($class)
	{
		$class 	= str_replace(EXT,'',$class);
		$name 	= ucfirst($class);
		if(!class_exists($name))
		{
			if ( ! file_exists(BASEPATH.'libraries/'.$name.EXT))
			{
				throw new TSystemException("Unable to load the requested class: ".$class);
			}
			include(BASEPATH.'libraries/'.ucfirst($class).EXT);
		}
		$class 		= strtolower($class);
		$classvar 	= ( ! isset($this->_varmap[$class])) ? $class : $this->_varmap[$class];
		$name 		= "T".$name;
		$this->$classvar = new $name;
	}
	/**
	 * 自己加载方法(加载autoload.php的配置)
	 * 
	 * @access	private
	 * @return	void
	 */
	private function _autoloader()
	{
		require_once(APPPATH.'config/autoload'.EXT);

		if ( ! isset($autoload))
		{
			return FALSE;
		}
		foreach (array('helper', 'plugin', 'vendor','sevice') as $type)
		{
			if (isset($autoload[$type]) AND count($autoload[$type]) > 0)
			{
				$this->$type($autoload[$type]);
			}
		}
		if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0)
		{
			// 加载数据库模块
			if (in_array('database', $autoload['libraries']))
			{
				$this->database();
				$autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
			}
			// 加载缓存模块
			if (in_array('cache', $autoload['libraries']))
			{
				$this->cache();
				$autoload['libraries'] = array_diff($autoload['libraries'], array('cache'));
			}
			// 加载功能库
			foreach ($autoload['libraries'] as $item)
			{
				$this->library($item);
			}
		}
	}
	/**
	 * 获得版本号
	 * 
	 * @access public
	 * @return string the version of Treacle framework
	 */
	public static function getVersion()
	{
		return '0.12';
	}
	/**
	 * 初始化错误管理.
	 * 
	 * 这个方法是设置错误管理异常处理
	 * @access public
	 * @return mixed
	 */
	public static function initErrorHandlers()
	{
		set_error_handler(array('Treacle','phpErrorHandler'),error_reporting());
		set_exception_handler(array('Treacle','exceptionHandler'));
	}
	/**
	 * 版权信息
	 * 
	 * @access public
	 * @return html
	 */
	public static function powered()
	{
		$url='http://www.treacle.cn/images/powered.gif';
		return '<a title="Powered by Treacle" href="http://www.treacle.cn/" target="_blank">
		<img src="'.$url.'" style="border-width:0px;" alt="Powered by Treacle" /></a>';
	}
	/**
	 * 异常处理,错误管理方法
	 * @access public
	 * @param mixed
	 */
	public static function exceptionHandler($exception)
	{
		require(BASEPATH.'exception/TErrorHandler'.EXT);
		$ErrorHandler = new TErrorHandler();
		return $ErrorHandler->handleError(null,$exception);
	}
	/**
	 * PHP 错误管理.
	 * 
	 * @access public
	 * @param integer 错误等级
	 * @param string 错误提示
	 * @param string 出错的文件名
	 * @param integer 出错文件名的行数
	 */
	public static function phpErrorHandler($errno,$errstr,$errfile,$errline)
	{
		if(error_reporting()!=0) throw new TPhpErrorException($errno,$errstr,$errfile,$errline);
	}
}
/*
+---------------------------------------------------------------------------
|   Last Modified By BoPo
|   Date: Wed Oct 03 14:43:02 CST 2007
+--------------------------------------------------------------------------
*/
?>